import settings from "@/settings";
import {getUserByOpenId} from "@/api/eyeCare.js";

/**
 * 获取token
 * @returns {String} token
 */
export const getToken = () => {
  return sessionStorage.getItem(settings.tokenKey);
}

/**
 * 设置token
 * @param {String} token 
 */
export const setToken = (token) => {
  if (!!sessionStorage.getItem(settings.tokenKey)) {
    return
  }
  sessionStorage.setItem(settings.tokenKey, token);
}

/**
 * 移除token
 */
export const removeToken = () => {
  sessionStorage.removeItem(settings.tokenKey);
}

export const getUser = async () => {
  if (!sessionStorage.getItem(settings.userKey)) {
    let resp = await getUserByOpenId(getToken());
    if (resp.code === 0) {
      sessionStorage.setItem(settings.userKey, JSON.stringify(resp.data))
    }
  }
  return JSON.parse(sessionStorage.getItem(settings.userKey));
}

export const setUser = (openId) => {
  if (!!sessionStorage.getItem(settings.userKey)) {
    return
  }
  getUserByOpenId(openId).then(resp => {
    if (resp.code === 0) {
      sessionStorage.setItem(settings.userKey, JSON.stringify(resp.data))
    }
  })
}